//
//  ViewController.swift
//  bluetooth
// http://www.cocoachina.com/articles/24389
//  Created by Evan on 2020/9/2.
//  Copyright © 2020 Evan. All rights reserved.
//

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, UITableViewDelegate, UITableViewDataSource, CBPeripheralDelegate {
    
    
    
    var tableView : UITableView!
    var centralManager:CBCentralManager?
    var peripheral:CBPeripheral?
    
    var arrayPer:[CBPeripheral] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.centralManager = CBCentralManager.init(delegate: self, queue: nil)
        
        tableView = UITableView(frame: self.view.bounds)
        self.view.addSubview(tableView)
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "uitableviewcellidentify")
        
        let btn = UIButton(frame: CGRect(x: 100, y: 500, width: (UIScreen.main.bounds.width - 200)/2, height: 50 ))
        btn.setTitle("查看地图", for: .normal)
        btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        self.view.addSubview(btn)
        
    }
    
    @objc func btnClick(sender:UIButton){
        centralManager?.stopScan()
        self.navigationController?.pushViewController(MapViewController(), animated: true)
    }
    
    
    
    // tableview
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrayPer.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "uitableviewcellidentify")!
        let p = self.arrayPer[indexPath.row]
        cell.textLabel?.text = p.name
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let p = self.arrayPer[indexPath.row]
        self.centralManager?.connect(p, options: nil)
    }
    
    
    // MARK: - 蓝牙
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch (central.state) {
        case .unknown:
            print(">>>CBCentralManagerStateUnknown");
            break;
        case .resetting:
            print(">>>CBCentralManagerStateResetting");
            break;
        case .unsupported:
            print(">>>CBCentralManagerStateUnsupported");
            break;
        case .unauthorized:
            print(">>>CBCentralManagerStateUnauthorized");
            break;
        case .poweredOff:
            print(">>>CBCentralManagerStatePoweredOff");
            break;
        case .poweredOn:
            do {
                print(">>>CBCentralManagerStatePoweredOn");
                // 开始扫描周围的外设。
                /*
                 -- 两个参数为Nil表示默认扫描所有可见蓝牙设备。
                 -- 注意：第一个参数是用来扫描有指定服务的外设。然后有些外设的服务是相同的，比如都有FFF5服务，那么都会发现；而有些外设的服务是不可见的，就会扫描不到设备。
                 -- 成功扫描到外设后调用didDiscoverPeripheral
                 */
                self.centralManager?.scanForPeripherals(withServices: nil, options: nil)
            }
            break;
        default:
            break;
        }
    }
    
    
    /// 发现外置蓝牙设备
    /// - Parameters:
    ///   - central: <#central description#>
    ///   - peripheral: <#peripheral description#>
    ///   - advertisementData: <#advertisementData description#>
    ///   - RSSI: <#RSSI description#>
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("查到蓝牙设备：\(peripheral.name ?? "")")
        if !self.arrayPer.contains(peripheral) {
            self.arrayPer.append(peripheral)
            self.tableView.reloadData()
        }
//        if let pn = peripheral.name {
//            if  pn.contains("mini") {
//                self.arrayPer.append(peripheral)
//                self.tableView.reloadData()
//
//            }
//        }
    }
    
    
    /// 链接成功
    /// - Parameters:
    ///   - central: <#central description#>
    ///   - peripheral: <#peripheral description#>
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("蓝牙链接成功：并停止扫描")
        // 停止扫描
        central.stopScan()
        
//        peripheral.delegate = self
        self.peripheral = peripheral
        let s = SCViewController()
        s.peripheral = peripheral
        self.present(s, animated: true, completion: nil)
        
//        CBUUID(string: "BA44B63A-1A21-435A-B75C-AA69A2974352"),
//        peripheral.discoverServices([CBUUID(string: "A8F93CCB-B9D6-4746-89FA-C2CC0804FC66")])
        
    }
    
    // 发现服务回调
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        print("发现服务回调")
        
//        var cfservice:CBService?
        peripheral.services?.forEach({ (sev) in
            //        硝酸盐  NITRATES
            //        A0D64EBA-AD9C-44EA-9E8B-9BBA41B74380
            //        辐射  RADIATION
            //        B95E9E0E-8372-44C2-ABB0-9D036307B55C
            //        电量  BATTERY_LVL
            //        273D6703-1F38-4FA1-836B-9B293ED3C6E6
            if sev.uuid.description == "A8F93CCB-B9D6-4746-89FA-C2CC0804FC66"
            {
                
                peripheral.discoverCharacteristics([CBUUID(string: "10175B2A-AA06-4200-B68C-A28AC752F30F")], for: sev)
            }else if sev.uuid.description == "BA44B63A-1A21-435A-B75C-AA69A2974352" {
                peripheral.discoverCharacteristics([CBUUID(string: "A0D64EBA-AD9C-44EA-9E8B-9BBA41B74380")], for: sev)
            }
        })
//        if let cfs = cfservice {
//            peripheral.discoverCharacteristics([CBUUID(string: "10175B2A-AA06-4200-B68C-A28AC752F30F")], for: cfs)
//        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?) {
        print("123123")
    }
    
    //从蓝牙设备获取返回值
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        /// 获取到查询的值
        if characteristic.uuid.description == "A0D64EBA-AD9C-44EA-9E8B-9BBA41B74380"{
            let alert = UIAlertController(title: "查询到的结果值：\(String(describing: characteristic.value))", message: "", preferredStyle: .alert)
            
            self.present(alert, animated: true, completion: nil)
        }
//        if let d = characteristic.value {
//            let s = String(data: d, encoding: .utf8)!
//            print("发现特征回调息didUpdateValueFor：\(characteristic.uuid)   \(s)")
//        }
        
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        print("didUpdateNotificationStateFor")
    }
    
    //发现特征回调
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        print("发现特征回调息didDiscoverCharacteristicsFor")
        
        service.characteristics?.forEach({ (cti) in
            if cti.uuid.description == "10175B2A-AA06-4200-B68C-A28AC752F30F" {
                self.peripheral?.readValue(for: cti)
//                self.characteristic = cti;
//                peripheral.setNotifyValue(true, for: cti)
                //                let s:Character = "1"
                let data = Data(bytes: [0x01], count: 1)
                self.peripheral?.writeValue(data, for: cti, type: .withResponse)
                print("手机向蓝牙发送的数据为:\(0x01)")
            }else if cti.uuid.description == "A0D64EBA-AD9C-44EA-9E8B-9BBA41B74380" {
                self.peripheral?.readValue(for: cti)
                // 读取指令返回值
                peripheral.discoverDescriptors(for: cti)
            }
//            peripheral.discoverDescriptors(for: cti)
        })
        
    }
    
    ///向蓝牙设备发送信息是否成功
    /// - Parameters:
    ///   - peripheral: <#peripheral description#>
    ///   - characteristic: <#characteristic description#>
    ///   - error: <#error description#>
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        print("向蓝牙设备发送信息是否成功：\(error)")
        let alert = UIAlertController()
        let ok = UIAlertAction(title: "查询指令发送成功", style: .default) { (ac) in
            self.peripheral?.discoverServices([CBUUID(string: "BA44B63A-1A21-435A-B75C-AA69A2974352")])
        }
        alert.addAction(ok)
        self.present(alert, animated: true, completion: nil)
        
    }
    
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
        print("123")
    }
}

